package cn.flying.base.security.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import cn.flying.base.common.constants.Constants;
import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.core.interceptor.AbstractRequestInterceptor;
import cn.flying.base.security.configuration.LoginUser;

/**
 * @description: 用户相关信息绑定到当前线程
 * @author: lvyong
 * @date: 2023年05月27日 12:23
 * @version: 1.0
 */
@Component
public class RequestUserDetailsInterceptor extends AbstractRequestInterceptor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("用户详情拦截：" + requestURI);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser;
        if (authentication != null && authentication.isAuthenticated()) {
            loginUser = (LoginUser) authentication.getPrincipal();
            Ft.ThreadLocal.set(Constants.TENANT_ID, loginUser.getTenantId());
            Ft.ThreadLocal.set(Constants.USER_ID, loginUser.getUserId());
            Ft.ThreadLocal.set(Constants.USER_NAME, loginUser.getUsername());
        } else {
            loginUser = new LoginUser();
        }
        logger.info("线程【{}】绑定租户【{}】的用户【{}-{}】信息", Thread.currentThread().getName(), loginUser.getTenantId(), loginUser.getUserId(), loginUser.getUsername());
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String tenantId = (String) Ft.ThreadLocal.get(Constants.TENANT_ID);
        String userId = (String) Ft.ThreadLocal.get(Constants.USER_ID);
        String userName = (String) Ft.ThreadLocal.get(Constants.USER_NAME);

        Ft.ThreadLocal.remove(Constants.TENANT_ID);
        Ft.ThreadLocal.remove(Constants.USER_ID);
        logger.info("线程【{}】清除租户【{}】的用户【{}-{}】信息", Thread.currentThread().getName(), tenantId, userId, userName);
    }

    /**
     * 设置拦截器的执行顺序，返回值越小优先级越高
     *
     * @return
     */
    @Override
    public Integer getOrder() {
        return Integer.MIN_VALUE;
    }
}
